package com.qi.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.core.util.ObjUtil;
import com.qi.common.Status;
import com.qi.pojo.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServerException.class)
    public AjaxResult serverExceptionHandler(ServerException e) {
        log.info("业务出现异常，原因：{}", e.getMsg());
        e.printStackTrace();
        if (ObjUtil.isEmpty(e.getStatus())) {
            return AjaxResult.error(e);
        }
        return AjaxResult.error(e.getStatus());
    }

    @ExceptionHandler(NotLoginException.class)
    public AjaxResult notLoginExceptionHandler(NotLoginException e) {
        log.info(e.getMessage());
        return AjaxResult.error(Status.AUTHENTICATION_ERROR);
    }

    @ExceptionHandler({NotRoleException.class, NotPermissionException.class})
    public AjaxResult authenticationException(Exception e) {
        log.info(e.getMessage());
        return AjaxResult.error(Status.PERMISSION_MISMATCHED);
    }


    @ExceptionHandler(NoResourceFoundException.class)
    public void noResourceFoundExceptionHandler(NoResourceFoundException e) {
        if (e.getMessage().contains("favicon.ico")) {
            return;
        }
        log.error("未找到资源异常，原因：{}", e.getMessage());
        e.printStackTrace();
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult serverExceptionHandler(Exception e) {
        log.error("系统出现异常，原因：{}", e.getMessage());
        e.printStackTrace();
        return AjaxResult.error(Status.ERROR);
    }
}
